"""
python main.py
"""

# main_runner.py
import os, time, sys
import subprocess
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from utils.config import load_config, update_config
from utils.logger import set_logger

# Define start and end dates
START_DATE = "2023-04-01T00:00:00Z"
END_DATE = "2025-03-01T23:59:59Z"

# Load the configuration file
config = load_config()
logger = set_logger()

# Setting the working directory to the directory of the script
os.chdir(os.path.dirname(__file__))

def run(start=START_DATE, end=END_DATE, delta_months=12):
    start_datetime = datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ")
    end_datetime = datetime.strptime(end, "%Y-%m-%dT%H:%M:%SZ")
    
    current_start = start_datetime
    while current_start < end_datetime:
        begin_time = time.time()
        # Set the current end as delta_months months after current start, minus 1 second
        current_end = current_start + relativedelta(months=delta_months) - timedelta(seconds=1)
        
        # Ensure the current end does not exceed the final end date
        if current_end > end_datetime:
            current_end = end_datetime
        
        # Print or yield the formatted datetime strings
        logger.info(f"start: {current_start.strftime("%Y-%m-%dT%H:%M:%SZ")}, \
                    end: {current_end.strftime("%Y-%m-%dT%H:%M:%SZ")}")

        # Update the configuration file with the current start and end datetimes
        update_config(config, 'start_datetime', current_start.strftime("%Y-%m-%dT%H:%M:%SZ"))
        update_config(config, 'end_datetime', current_end.strftime("%Y-%m-%dT%H:%M:%SZ"))

        # Run the scripts
        os.chdir(os.path.dirname(__file__))
        subprocess.run(["python", "00_cn_locations.py"])
        subprocess.run(["python", "01_create_query_log_db.py"])
        subprocess.run(["python", "02_search_videos.py"])
        subprocess.run(["python", "03_chunk_tables.py"])
        subprocess.run(["python", "04_get_video_comments.py"])
        
        # Update current_start for the next block to be 1 second after the current end
        current_start = current_end + timedelta(seconds=1)

        logger.info(f"Time taken for the block: {time.time() - begin_time:.2f} seconds.\n")



if __name__ == "__main__":
    start = time.time()
    run()
    end = time.time()
    logger.info(f"Total time taken to run the scripts: {end - start:.2f} seconds.")
